<?php
/**
 * Created by PhpStorm.
 * User: sunfan
 * Date: 2017/8/12
 * Time: 9:53
 */

namespace Common\Model;


use Think\Model;

class ProductModel extends Model
{
    protected $_validate = array(
        array('title','require','请填写商品名称'),
        array('category_id','checkCate','请选择商品分类',0,'callback'), // 自定义函数验证密码格式
        array('price','require','请填写商品价格'), //
        array('stock','require','请填写商品库存'), //
    );

    // 验证商品分类
    protected function checkCate(){
        $cate = I("post.category_id",0,'intval');
        if($cate){
            return true;
        }else{
            return false;
        }
    }

    //  添加数据库
    public function store(){
        if($this->create()){
          $data = I('post.');
          $sliders = $data['slider'];
          unset($data['slider']);
          $data['create_time'] = date('Y-m-d H:i:s');
          $id = $this->add($data);
          if($id){
              $this->slider($sliders,$id);
              return $id;
          }
          $this->error = "添加失败";
        }
        return false;
    }

    // 修改数据库
    public function update(){
        if($this->create()){
            $data = I('post.');
            $sliders = $data['slider'];
            $id = $data['id'];
            unset($data['slider']);
            unset($data['id']);
            $slider_id = $data['slider_id']?$data['slider_id']:array();
            unset($data['slider_id']);
            $this->where(array('id'=>$id))->save($data);
            $this->slider_update($sliders,$slider_id,$id);
            return true;
        }
        return false;
    }

    // 图片添加
    private function slider($list = array(),$id){
       foreach($list as $v){
           $data = array('path'=>$v,'product_id'=>$id);
           D("ProSlider")->add($data);
       }
    }

    // 图片编辑
    private function slider_update($list = array(),$ids,$id=0){
        $str = implode(',',$ids);
        $query = D("ProSlider")->where(array('id'=>array('in',$str)))->select();
        $arrs = array();
        foreach($query as $l){
          $arrs[] = $l['path'];
        }
        foreach($list as $v){
           if(!in_array($v,$arrs)){
               $data = array('path'=>$v,'product_id'=>$id);
               D("ProSlider")->add($data);
           }
        }
    }
}